<?php
if (!defined("APP_PATH")) {
    define('APP_PATH',__DIR__.'/../application/');
    // 加载框架引导文件
    require  __DIR__.'/../thinkphp/start.php';
}
echo "<pre>";
//每10秒触发一次
if(config("site.static_switch")) static_profit();

function static_profit()
{
    $debug = config("app_debug");
    if (php_sapi_name() != 'cli' && !$debug) {
        echo '只能在cli模式下或者开启调试模式运行：' . date('Y-m-d H:i:s') . "\r\n";die;
    }
    \think\Log::info("开始静态收益");
    echo '开始执行的时间：'.date('Y-m-d H:i:s')."\r\n";
    $redis = rds();
    $bkey = 'static_profit';
    if($debug) delkey($redis,$bkey);
    $op = $redis->set($bkey,1,['NX','EX'=>9]);
    if(!$op){
        echo '请勿频繁操作：'.date('Y-m-d H:i:s')."\r\n";
        goto END;
    }

    //校验缓存里的投资数据是否缺失
    $users_count = \db('user')->where(['credit1'=>['>',0]])->count();
    $rds_tzcount = $redis->hLen(REDIS_PREFIX.'user_tz');
    if($users_count != $rds_tzcount){
        $users = \db('user')->where(['credit1'=>['>',0]])->field('id,credit1')->select();
        $arr = [];
        foreach($users as $user){
            $arr['user_'.$user['id']] = $user['credit1'];
        }
        if($arr) $redis->hMset(REDIS_PREFIX.'user_tz',$arr);//重新设置投资额度
        unset($arr,$users);
    }
//    $day = date('Ymd');
    $lua_static = <<<LUA
    local all_user_tz = redis.call('hGetALL',KEYS[1])
    local i = 1
    local key
    if all_user_tz ~= false
    then
        for k,vel in ipairs(all_user_tz) do
            if i%2==0
            then
                local add_sy = vel*ARGV[1]/ARGV[2]
                redis.call('hIncrByFloat',KEYS[2],key,add_sy)
                redis.call('hIncrByFloat',KEYS[3],key,add_sy)
            else
                key = vel
            end
            i = i + 1
        end
    end
    return true
LUA;
    //                                        静态参数           每天1% 10秒发一次
    $ret = $redis->eval($lua_static,[REDIS_PREFIX.'user_tz',REDIS_PREFIX.'user_sy',REDIS_PREFIX.'static_sy',config("site.static_bi")/100,8640],3);
//    var_dump($ret,$redis->hGetAll('user_tz'),$redis->hGetAll('user_sy'));
    if($ret === false){
        \think\Log::error("结算静态奖励失败");
        echo '执行失败：'.date('Y-m-d H:i:s')."\r\n";
    }

    delkey($redis,$bkey);
    END:
    \think\Log::info("结束静态收益");
    echo '结束执行的时间：'.date('Y-m-d H:i:s')."\r\n";
}


